package com.theaf.basemodule.dao;

import com.theaf.basemodule.common.model.SysUser;
import com.theaf.core.repo.base.BaseRepository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import javax.transaction.Transactional;
import java.util.List;

/**
 * 用户DAO
 *
 * @author songwenke
 * @create 2017-12-26 10:51
 **/
@Repository
public interface UserDAO extends BaseRepository<SysUser , Long> {
    SysUser findByUserName(String userName);

    @Query(nativeQuery=true,value = "select a.* from sys_user a where a.user_name like %:userName% and a.mobile like %:mobile%" +
            " and a.org_id in :orgIds and (a.org_id in :rangs or :rangs is null)" +
            " and a.cname like %:cname% and (a.pos_id=:posId or :posId is null) and a.state<>3 /*#pageable*/")
    Page<SysUser> findCondition(@Param("userName") String userName,
                                @Param("mobile") String mobile,
                                @Param("orgIds") List<Long> orgIds,
                                @Param("posId") Long posId,
                                @Param("rangs") List<Long> rangs,
                                @Param("cname") String cname,
                                Pageable pageable);

    @Modifying
    @Transactional
    @Query(nativeQuery=true,value = "delete from sys_use_auth a " +
            "where EXISTS (select * from sys_resource t,sys_resource y " +
            "where t.id=a.res_id and t.level_code like y.level_code||'%' and y.id=:menuId)")
    void deleteResource(@Param("menuId") Long menuId);
}
